package com.fuhao.member.utils;

import com.alibaba.fastjson.JSONObject;
import com.fuhao.core.Constants.Constants;
import com.fuhao.core.base.BaseApiService;
import com.fuhao.core.base.BaseResponse;
import com.fuhao.core.transaction.RedisDataSoureceTransaction;
import com.fuhao.core.utils.GenerateToken;
import com.fuhao.dto.input.MemberLoginInpDTO;
import com.fuhao.member.entity.MemberEntity;
import com.fuhao.member.entity.MemberTokenEntity;
import com.fuhao.member.mapper.UserTokenMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;

/**
 * @author zhang
 * @title: token保持唯一性
 */
@Component
public class TokenUniqueUtils extends BaseApiService<JSONObject> {
    @Autowired
    private UserTokenMapper userTokenMapper;
    @Autowired
    private RedisDataSoureceTransaction dataSoureceTransaction;
    @Autowired
    private GenerateToken generateToken;

    /**
     * 登录唯一性
     * @param memberEntity
     * @param memberLoginInpDTO
     * @return
     */
    public BaseResponse<JSONObject> CheckTokenUnique(MemberEntity memberEntity, MemberLoginInpDTO memberLoginInpDTO){
        Long userid = memberEntity.getUserid();
        String loginType = memberLoginInpDTO.getLoginType();
        MemberTokenEntity memberTokenEntity = userTokenMapper.selectByUserIdAndLoginType(userid, loginType);
        TransactionStatus transactionStatus = null;
        try {
            //3.1开启redis、数据库事务
            transactionStatus = dataSoureceTransaction.begin();
            //3.2若token不为空
            if (memberTokenEntity != null) {
                String token = memberTokenEntity.getToken();
                //3.2.1删除redis的token
                boolean isRemoveToken = generateToken.removeToken(token);
                int resultRow = userTokenMapper.updateAvailabilityByToken(token);
                //3.2.2当数据库更新失败回滚
                if(!toDaoResult(resultRow)){
                    dataSoureceTransaction.rollback(transactionStatus);
                    return setResultError("系统错误!");
                }
            }
            //3.3生产token
            String prefix = Constants.MEMBER_TOKEN_KEYPREFIX + memberLoginInpDTO.getLoginType();
            String token = generateToken.createToken(prefix,  userid + "",
                    Constants.MEMBRE_LOGIN_TOKEN_TIME);
            //4.插入数据库
            MemberTokenEntity memberTokenDo = new MemberTokenEntity();
            memberTokenDo.setUserId(userid);
            memberTokenDo.setLoginType(loginType);
            memberTokenDo.setDeviceInfor(memberLoginInpDTO.getDeviceInfor());
            memberTokenDo.setToken(token);
            int result = userTokenMapper.insertUserToken(memberTokenDo);
            //4.1插入失败，回滚
            if (!toDaoResult(result)) {
                dataSoureceTransaction.rollback(transactionStatus);
                return setResultError("系统错误！");
            }
            //5.返回token信息
            JSONObject tokenDate = new JSONObject();
            tokenDate.put("token", token);
            //6.提交事务
            dataSoureceTransaction.commit(transactionStatus);
            return setResultSuccess(tokenDate);
        } catch (Exception e) {
            try{
                //回滚
                dataSoureceTransaction.rollback(transactionStatus);
            }catch (Exception e1){}
            return setResultError("系统错误！");
        }
    }
}
